package wikigearsconnector.connect.connector;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HostParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.eclipse.core.internal.content.ContentType;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import wikigearsconnector.ConnectorPlugin;
import wikigearsconnector.connect.customrequesentity.CustomFileRequestEntity;
import wikigearsconnector.connect.customrequesentity.CustomStreamPartSource;

public class Connector {

	private static final String GOOGLE_LINK_START = "/_ah";
	private static final String HTTP_LINK_START = "http";
	private String blobURL;
	private String projectName = "";

	// modify it!!!!
	private String login;// = "test@example.com";
	private String passwd;// = "passwd";
	private String host;// = "127.0.0.1";
	private int port;// = 8888;
	private String protocol = HTTP_LINK_START;

	private HttpClient client;

	public Connector(String host, int port, String login, String passwd,
			String projectName) {
		this.login = login;
		this.passwd = passwd;
		this.host = host;
		this.port = port;
		this.projectName = projectName;
	}

	/**
	 * Performs connector initializaion
	 * @return {@link IStatus} containing initialization result. Would be {@link Status#OK_STATUS},
	 * if initialization succeeded. Otherwise - would contain error msg, and, possibly, Exception for it
	 * 
	 */
	public IStatus init() {
		client = new HttpClient();
		HostConfiguration hc = new HostConfiguration();
		HttpHost hoost = new HttpHost(host, port, Protocol
				.getProtocol(protocol));
		hc.setHost(hoost);
		client.setHostConfiguration(hc);
		PostMethod post = new PostMethod("/storeblob");

		try {

			post.setParameter("login", login);
			post.setParameter("passwd", passwd);
			client.executeMethod(post);
			String res = post.getResponseBodyAsString();
			if (res.startsWith(HTTP_LINK_START) || res.startsWith(GOOGLE_LINK_START)) {
				blobURL = res;
			} 
			else {
				ConnectorPlugin.getDefault().getLog().log(new Status(Status.ERROR, ConnectorPlugin.PLUGIN_ID,"Invalid response " + res));
				return new Status(IStatus.ERROR, ConnectorPlugin.PLUGIN_ID, "Error getting response. See error log for details." );
				
			}
		} catch (HttpException e) {
			e.printStackTrace();
			ConnectorPlugin.log(e);
			return new Status(IStatus.ERROR, ConnectorPlugin.PLUGIN_ID, "HTTP connection error. " + e.getLocalizedMessage(), e);
		} catch (IOException e) {
			e.printStackTrace();
			ConnectorPlugin.log(e);
			return new Status(IStatus.ERROR, ConnectorPlugin.PLUGIN_ID, "I/O error. " + e.getLocalizedMessage(), e);
		}
		return Status.OK_STATUS;

	}

	public void commitResource(URL resource, String fName) {
		try {

			URI resURI = null;
			try {
				resURI = resource.toURI();
			} catch (URISyntaxException e1) {
				ConnectorPlugin.log(e1);
				e1.printStackTrace();
			}

			InputStream is = resource.openStream();
			PostMethod post = new PostMethod(blobURL);

			fName = "/" + projectName + "/" + fName;

			CustomStreamPartSource cfps = new CustomStreamPartSource(fName, is);
			FilePart fp = new FilePart(fName, cfps, "multipart/form-data",
					"UTF-8");

			post.setRequestEntity(new MultipartRequestEntity(new Part[] { fp },
					new HttpMethodParams()));// new
			// CustomFileRequestEntity(is,"imsge/gif",
			// 0));
			try {
				HttpConnectionManagerParams hmp = new HttpConnectionManagerParams();
				client.getHttpConnectionManager().setParams(hmp);
				HostConfiguration hc = new HostConfiguration();
				HttpHost hoost = new HttpHost(host, port, Protocol
						.getProtocol(protocol));
				hc.setHost(hoost);
				client.setHostConfiguration(hc);
				client.executeMethod(post);
				String s = post.getResponseBodyAsString();
				return;
			} catch (HttpException e) {				
				e.printStackTrace();
				ConnectorPlugin.log(e);
			} catch (IOException e) {
				e.printStackTrace();
				ConnectorPlugin.log(e);
			}
		} catch (IOException e2) {
			e2.printStackTrace();
			ConnectorPlugin.log(e2);
		}
	}

}
